package com.example.g7640.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.g7640.entity.Score;
import com.example.g7640.exception.BizException;
import com.example.g7640.mapper.ScoreMapper;
import com.example.g7640.service.ScoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.g7640.util.RoleCheckUtil;
import com.sun.org.apache.bcel.internal.generic.LADD;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.OptionalDouble;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2024-03-18
 */
@Service
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements ScoreService {

    @Resource
    ScoreMapper scoreMapper;

    @Override
    public Boolean add(Score score) {
//        RoleCheckUtil.checkCustomer();
        Score s = new Score();
        if (score.getVid() == null) {
            throw new BizException("vid is null");
        }
        if (score.getScore() == null) {
            throw new BizException("score is null");
        }
        s.setScore(score.getScore() * 10);
        s.setVid(score.getVid());
        s.setUpdatedAt(LocalDateTime.now());
        s.setCreatedAt(LocalDateTime.now());
        this.save(s);
        return true;
    }

    @Override
    public Double getAvg(Integer vid) {
//        RoleCheckUtil.checkCustomer();
        LambdaQueryWrapper<Score> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Score::getVid, vid);
        List<Score> l = scoreMapper.selectList(wrapper);
        OptionalDouble result = l.stream().mapToDouble(Score::getScore).average();
        if(result.isPresent()) {
            return result.getAsDouble()/10;
        } else {
            return (double) -1;
        }
    }
}
